﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Net;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Data.Linq;
using System.IO;
using System.Management;
using System.Configuration;
using System.Xml;
using System.Data.SqlClient;
using MSBTC.Model;
using MSBTC.WinForms;
using System.Security.AccessControl;

namespace MSBTC
{
    public class FormHelpers
    {
        public readonly string ConfigXML = "C:\\Database Connection Setting.xml";
        public string DBUsername, DBPassword, DBPort, DBAddress;
        public string ex;
        //public SqlConnection DBSql = new SqlConnection();
        private static string usrn;
        private static string txts;
        TextBox cleared = new TextBox();
        public string error;
        private static string ProjName;
        private static int MatEsti;
        private static string Print;
        private static string cost, budget, remain;

        public string usrname(string name)
        {
            usrn = name;
            return usrn;
        }
        public string GetName()
        {
            return usrn;
        }

        public string getPname(string name)
        {
            ProjName = name;
            return ProjName;
        }
        public string Pname()
        {
            return ProjName;
        }

        public int MEname()
        {
            return MatEsti;
        }

        public string GetPrintStat(string stat)
        {
            Print = stat;
            return Print;
        }
        public string PrintStat()
        {
            return Print;
        }

        public string GetCost(string name)
        {
            cost = name;
            return cost;
        }
        public string Cost()
        {
            return cost;
        }

        public string GetBudget(string name)
        {
            budget = name;
            return budget;
        }
        public string Budget()
        {
            return budget;
        }

        public string GetRemain(string name)
        {
            remain = name;
            return remain;
        }
        public string Remain()
        {
            return remain;
        }

        public bool Save_Configuration()
        {
            try
            {
                UnicodeEncoding encc = new UnicodeEncoding();
                XmlTextWriter xmlwrter = new XmlTextWriter(ConfigXML, encc);

                xmlwrter.Indentation = 1;
                xmlwrter.Formatting = Formatting.Indented;
                xmlwrter.WriteStartDocument();
                xmlwrter.WriteStartElement("ConnectionString");
                xmlwrter.WriteElementString("DESCRIPTION", "Description(SERVER INFO):" +
                                     " This is a system generated configuration file." +
                                     "\n" + " Changes being made to his file will " +
                                     "affect the overall system.");
                xmlwrter.WriteElementString("Username", DBUsername);
                xmlwrter.WriteElementString("Password", DBPassword);
                xmlwrter.WriteElementString("IPAddress", DBAddress);
                xmlwrter.WriteElementString("Port", DBPort);
                xmlwrter.Close();

                return true;
            }
            catch (Exception exc)
            {
                ex = exc.Message.ToString();
                return false;
            }
        }

        public bool Read_Configuration()
        {
            XmlDocument xmlrder = new XmlDocument();
            xmlrder.Load(ConfigXML);
            try
            {
                string dbpass = xmlrder.SelectSingleNode("ConnectionString/Password").InnerText;
                string dbport = xmlrder.SelectSingleNode("ConnectionString/Port").InnerText;
                string dbuid = xmlrder.SelectSingleNode("ConnectionString/Username").InnerText;
                string dbip = xmlrder.SelectSingleNode("ConnectionString/IPAddress").InnerText;

                DBConnect(dbip.Trim(), dbport, dbuid, dbpass);
                return true;
            }
            catch (Exception exc)
            {
                ex = exc.Message.ToString();
                return false;
            }
        }

        public bool DBConnect(string dbip, string dbport, string dbuid, string dbpass)
        {
            //string myDBConnectionString; = String.Format( 
            //    ConfigurationManager.ConnectionStrings["PMS_Context"].ConnectionString,
            //    dbip, dbport, dbuid, dbpass);
            try
            {
                Configuration confg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                confg.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings("PMS_Context", String.Format(
                    "Network Library=DBMSSOCN;Persist Security Info=false;Data Source={0},{1};User ID={2};Password={3};Initial Catalog=MSBTC_DB;",
                     dbip.Trim(), dbport, dbuid, dbpass), "System.Data.SqlClient"));

                //AddFileSecurity(myDBConnectionString, @"DomainName\AccountName", FileSystemRights.FullControl, AccessControlType.Allow);
                confg.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("connectionStrings");

                DBPort = dbport;
                DBAddress = dbip;
                DBUsername = dbuid;
                DBPassword = dbpass;
                return true;
            }
            catch (Exception exc)
            {
                ex = exc.Message.ToString();
                return false;
            }
        }

        public bool CheckConfig()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;
            if (section == null)
            {
                try
                {
                    Read_Configuration();
                    return true;
                }
                catch (Exception e)
                {
                    ex = e.Message.ToString();
                    return false;
                }
            }
            else
            {
                return true;
            }
        }

        public bool ResetConfig()
        {
            try
            {
                Configuration confg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                confg.ConnectionStrings.ConnectionStrings.Remove("PMS_Context");
                confg.Save();
                ConfigurationManager.RefreshSection("connectionStrings");
                return true;
            }
            catch (Exception exc)
            {
                ex = exc.Message.ToString();
                return false;
            }
        }

        public static void AddFileSecurity(string fileName, string account,
            FileSystemRights rights, AccessControlType controlType)
        {
            // Get a FileSecurity object that represents the
            // current security settings.
            FileSecurity fSecurity = File.GetAccessControl(fileName);

            // Add the FileSystemAccessRule to the security settings.
            fSecurity.AddAccessRule(new FileSystemAccessRule(account,
                rights, controlType));

            // Set the new access settings.
            File.SetAccessControl(fileName, fSecurity);

        }
        public bool SpecChar(string giventxt, TextBox clear)
        {
            txts = giventxt;
            cleared = clear;

            if(txts.Contains("@"))
            {
                cleared.Clear();
                return false;
               //MessageBox.Show("Special Characters are not allowed", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
               
            }
            else if(txts.Contains("'"))
            {
                cleared.Clear();
                return false;
            }
            else if(txts.Contains("-") || txts.Contains(";")) 
            {
                cleared.Clear();
                return false;
            }
            else if(txts.Contains("#") || txts.Contains("|") || txts.Contains("/")) 
            {
                cleared.Clear();
                return false;
            }
            else if(txts.Contains("$") || txts.Contains("'") || txts.Contains(":")) 
            {
                cleared.Clear();
                return false;
            }
            else if(txts.Contains("%") || txts.Contains("}") || txts.Contains("[")) 
            {
                cleared.Clear();
                return false;
            }
            else if(txts.Contains("^") || txts.Contains("]") || txts.Contains("{")) 
            {
                cleared.Clear();
                return false;
            }
            else if(txts.Contains("&") || txts.Contains(".") || txts.Contains("\'")) 
            {
                cleared.Clear();
                return false;
            }
            else if(txts.Contains(")") || txts.Contains("<") || txts.Contains(",")) 
            {
                cleared.Clear();
                return false;
            }
            else if(txts.Contains("*") || txts.Contains("?") || txts.Contains(">")) 
            {
                cleared.Clear();
                return false;
            }
            else if (txts.Contains("!") || txts.Contains("(") || txts.Contains("+"))
            {
                cleared.Clear();
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}
